import torch
import numpy as np
from torch.utils.data import Dataset
from torch.utils.data import DataLoader


class DiabetesDataset(Dataset):
    # Initialize data source
    def __init__(self, filepath):
        xy = np.loadtxt(filepath, delimiter=',', dtype=np.float32)
        self.len = xy.shape[0]
        self.x_data = torch.from_numpy(xy[:, :-1])
        self.y_data = torch.from_numpy(xy[:, [-1]])

    # Get the designative element
    def __getitem__(self, index):
        return self.x_data[index], self.y_data[index]

    # Get row numbers
    def __len__(self):
        return self.len


dataset = DiabetesDataset('../dataset/diabetes.csv')
train_loader = DataLoader(dataset=dataset,
                          batch_size=32,
                          shuffle=True,
                          num_workers=2)
train_features, train_labels = next(iter(train_loader))
print(f"Feature batch shape: {train_features.size()}")
print(f"Labels batch shape: {train_labels.size()}")


# Design model using Class
class DiabeteModel(torch.nn.Module):
    def __init__(self):
        super(DiabeteModel, self).__init__()
        # Linear transformation
        self.linear_01 = torch.nn.Linear(8, 6)
        self.linear_02 = torch.nn.Linear(6, 4)
        self.linear_03 = torch.nn.Linear(4, 1)
        # Activate function
        self.sigmoid = torch.nn.Sigmoid()
        # Forward

    def forward(self, x):
        x = self.sigmoid(self.linear_01(x))
        x = self.sigmoid(self.linear_02(x))
        x = self.sigmoid(self.linear_03(x))
        return x


diabeteModel = DiabeteModel()
# Construct loss and optimizer
criterion = torch.nn.BCELoss(size_average=True)
optimizer = torch.optim.SGD(diabeteModel.parameters(), lr=0.01)
for epoch in range(100):
    for i, data in enumerate(train_loader, 0):
        # Prepare data
        inputs, labels = data
        # Forward
        y_pred = diabeteModel(inputs)
        loss = criterion(y_pred, labels)
        print(epoch, i, loss.item())
        # Backward
        optimizer.zero_grad()
        loss.backward()
        # Update
        optimizer.step()
print('w1 = ', diabeteModel.linear_01.weight)
print('w2 = ', diabeteModel.linear_02.weight)
print('w3 = ', diabeteModel.linear_03.weight)
print('bias1 = ', diabeteModel.linear_01.bias)
print('bias2 = ', diabeteModel.linear_02.bias)
print('bias3 = ', diabeteModel.linear_03.bias)